package admin

import (
	"github.com/labstack/echo"
	"github.com/sirupsen/logrus"
	"net/http"
	"src/config"
	"src/model"
	"src/util/context"
	"src/util/log"
)

var adminreplyLogger = log.GetLogger()

func writeAdminreplyLoggerLoggerLog(funcName, errMsg string, err error) {
	adminreplyLogger.WithFields(logrus.Fields{
		"package":  config.LogMessage + "/admin",
		"file":     "reply.go",
		"function": funcName,
		"err":      err,
	}).Warn(errMsg)
}

func DeleteReply(c echo.Context) error {
	reply := model.Reply{}
	err := c.Bind(&reply)
	if err != nil {
		writeAdminreplyLoggerLoggerLog("DeleteReply", "1", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}

	id := context.GetJWTUsername(c)
	_, err = model.FindAdmin(id)
	if err != nil {
		writeAdminreplyLoggerLoggerLog("DeleteReply", "2", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.Hasnotpower)
	}

	reply, err = model.DeleteReply(reply.ID.Hex(), reply.UserID, true)
	if err != nil {
		writeAdminreplyLoggerLoggerLog("DeleteReply", "3", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorReplyDelete)
	}

	err = model.UpdateCommentReply(reply.TopicID, -1)
	if err != nil {
		writeAdminreplyLoggerLoggerLog("DeleteReply", "4", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateCommentReply)
	}

	err = model.UpdateForumpostReply(reply.ForumPostId, -1)
	if err != nil {
		writeAdminreplyLoggerLoggerLog("DeleteReply", "5", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateForumpostReply)
	}

	r := []model.Reply{}
	r, err = model.GetReplyByReplyALL(reply.ID.Hex())
	if err != nil {
		writeAdminreplyLoggerLoggerLog("DeleteReply", "6", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorReplyGet)
	}
	for i := 0; i < len(r); i++ {
		_, _ = model.DeleteReply(r[i].ID.Hex(), r[i].UserID, true)
	}

	err = model.UpdateForumpostScore(reply.ForumPostId, -config.ReplyScore)
	if err != nil {
		writeAdminreplyLoggerLoggerLog("DeleteReply", "7", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateForumpostScore)
	}

	err = model.UpdateCommentScore(reply.TopicID, -config.ReplyScore)
	if err != nil {
		writeAdminreplyLoggerLoggerLog("DeleteReply", "8", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateCommentScore)
	}
	return context.RetData(c, "")
}
